<template>
  <view class="m-big-box">
    <view v-if="hasLocationAuth||(type.indexOf('self')==-1)">
      <view class="location-icon">
        <u-icon name="map-fill" size="40rpx"></u-icon>
      </view>
      <view class="box-text">
        <!--   是否显示1级行政区     -->
        <text v-if="isShowAdlv1">{{ info.adlv1Name }}</text>
        <!--   是否显示2级行政区     -->
        <text v-if="isShowAdlv2">{{ info.adlv2Name }}</text>
        <!--   是否显示3级行政区     -->
        <text v-if="isShowAdlv3">{{ info.adlv3Name }}</text>
      </view>
    </view>
    <view
        @click="chooseLocation"
        v-else>
      <view class="location-icon">
        <u-icon name="map" size="40rpx"></u-icon>
      </view>
      <view class="box-text">开启定位权限</view>
    </view>

  </view>
</template>

<script>
import request from '../../libs/request';

export default {
  props: {
    /**
     * 类型
     * 自定义的位置：custom
     * 自己的位置：self
     * 自己的位置加上历史记录：selfHistory
     */
    type: {
      type: String,
      default: 'self'
    },
    /**
     * 上次选择的位置
     * 只有type为self-history时才有用
     */
    lastLocation: {
      type: String,
      default: ''
    },
    /**
     * 是否显示1级地址
     */
    isShowAdlv1: {
      type: Boolean,
      default: false
    },
    /**
     * 是否显示2级地址
     */
    isShowAdlv2: {
      type: Boolean,
      default: false
    },
    /**
     * 是否显示3级地址
     */
    isShowAdlv3: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      hasLocationAuth: false,
      info: {
        adlv1Name: '',
        adlv2Name: '',
        adlv3Name: '',
      },
    };
  },
  mounted() {
    uni.$on('getLocationSelf', (res) => {
      if (this.type === 'self') {
        this.info = res;
      }
    });
    if (this.type === 'self') {
      // 如果类型是self
      let storageSync = uni.getStorageSync("addressSelf");
      // 获取存储时间
      let storageTime = uni.getStorageSync("addressSelfTime")
      // 如果有存储，且存储时间在三分钟内
      if (storageSync && (new Date().getTime() - storageTime < 3 * 60 * 1000)) {
        this.info = storageSync;
        this.hasLocationAuth = true;
        console.log('storageSync', storageSync);
        uni.$emit('getLocationSelf', storageSync);
        return;
      }
    }
    if (this.type === 'self' || this.type === 'selfHistory') {
      this.getLocation();
    }
  },
  methods: {
    /**
     * 根据经纬度获取位置
     */
    getByLngAndLat(lng, lat) {
      uni.showLoading({title: '获取位置中...'});

      request.request({
        url: "/api-lbs-web/ad/getByLngAndLat",
        data: {
          lng,
          lat
        },
        stateSuccess: (res) => {
          this.info = res.data;
          if (this.type === 'self') {
            uni.setStorageSync("addressSelf", this.info);
            uni.setStorageSync("addressSelfTime", new Date().getTime());
            uni.$emit('getLocationSelf',  this.info);
          }
          uni.hideLoading();
        },
        stateFail: (res) => {
          console.log(res);
        }
      });
    },
    chooseLocation() {
      if (!this.hasLocationAuth) {
        // 前往开启定位权限
        uni.openSetting({
          success: (res) => {
            console.log(res);
            if (res.authSetting['scope.userLocation']) {
              // 拥有定位权限
              this.hasLocationAuth = true;
              this.getLocation();
            }
          }
        });
      }
    },
    /**
     * 获取当前位置
     */
    getLocation() {
      uni.getLocation({
        success: (res) => {
          console.log(res);
          // 经度
          const lng = res.longitude;
          // 纬度
          const lat = res.latitude;
          this.getByLngAndLat(lng, lat);
          // 拥有定位权限
          this.hasLocationAuth = true;

        }, fail: (err) => {
          console.log(err);
          if (err.errMsg.indexOf("getLocation:fail auth deny") != -1) {
            uni.showToast({title: '请开启定位权限', icon: 'none', duration: 2000});
            // 没有定位权限
            this.hasLocationAuth = false;
            return false;
          }
          if (err.errMsg.indexOf("getLocation:fail the api need to be declared in the requiredPrivateInfos field in app.json/ext.json") != -1) {
            uni.showToast({title: '未声明定位权限作用', icon: 'none', duration: 2000});
            // 没有定位权限
            this.hasLocationAuth = false;
            return false;
          }

        }
      });
    },
  }
}

</script>

<style lang="scss" scoped>
.m-big-box {
  position: relative;
  display: inline-block;
  padding: 10rpx 10rpx 10rpx 50rpx;
  color: #333333;
  font-weight: bold;
  letter-spacing: 1rpx;

  .location-icon {
    position: absolute;
    left: 10rpx;
    margin-right: 10rpx;
  }

  .box-text {
    display: inline-block;
    font-size: 30rpx;
  }
}

.m-big-box:active {
  .box-text {
    transform: scale(.95);
  }
}
</style>